package com.example.login;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
@Component
public class LoginFailHandler extends SimpleUrlAuthenticationFailureHandler {

    @Value("${login_context_host}")
    private String login_context_host;

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        // 在会话中存储错误信息
        HttpSession session = request.getSession();
        session.setAttribute("loginError", exception.getMessage());
        // 重定向到 /login?error
        setDefaultFailureUrl(login_context_host + "/login");
        super.onAuthenticationFailure(request, response, exception);
    }
}